/*
 * * * * * * * * * * * * * * *
 *	author: ma
 *	date: 2020-09-20
 *	function: 封装websocket为了即时同屏
 * * * * * * * * * * * * * * *
 */

function Webclient(ws) {
  this.ws = ws;
  this.websocket = null;
  this.status = "close";
}

Webclient.prototype = {
  constructor: Webclient,
  connect: function () {
    var that = this;
    that.websocket = new WebSocket(that.ws);
    that.websocket.onopen = function (e) {
      console.log("连接成功", e);
      that.status = "open";
      that.getMessage1()
    };
  },
  sendMessage: function (event, param) {
    // 处理传入的参数
    if (typeof event !== "string") {
      alert("事件为字符串");
      return false;
    }

    var obj = {
      event: event,
      param: param || "",
    };
    this.websocket.send(JSON.stringify(obj));
  },
  // 得到回调
  getMessage: function () {
    var that = this;
    return new Promise(function (resolve, reject) {
      that.websocket.onmessage = function (e) {
        var obj = JSON.parse(e.data);
        resolve(obj);
      };
    });
  },
  // 得到回调
  getMessage1: function () {
    var that = this;
    that.websocket.onmessage = function (result) {
      var event = JSON.parse(result.data).event;
      // 开始播放
      if (event == 'playvideo') {
        player.start()
        player.play()
      }

      // 暂停播放
      if (event == 'pausevideo') {
        player.pause()
      }

      // 继续播放
      if (event == 'continuevideo') {
        player.play()
      }

      // 快进视频
      if (event == 'speedvideo') {
        player.currentTime = player.currentTime + 5;
      }

      // 快退视频
      if (event == 'backvideo') {
        player.currentTime = player.currentTime - 5;
      }

      // 静音视频
      if (event == 'mutedvideo') {
        player.muted = player.muted ? false : true;
      }
    };
  },
  // 心跳认证
  heartCheck: function () {},
  // 关闭
  closeWebclient: function () {
    this.status = "close";
    this.websocket.send("close");
    this.websocket.close();
    console.log("关闭连接");
  },
};
